package com.enjoyor.soa.traffic.util.helper;

import com.alibaba.fastjson.JSONObject;
import com.enjoyor.soa.traffic.util.enums.ejcds.EnumEjcdsCommon;
import oracle.spatial.geometry.JGeometry;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.util.*;

public class UserLogHelper {
    private static final Logger LOGGER = Logger.getLogger(UserLogHelper.class.getClass());

    public static String getUpdateContent(Object originalObj, Object changedObj, String keyName, String objName) {
        return getUpdateContent(originalObj, changedObj, keyName, objName, false, false, null);
    }
    public static String getUpdateContent(Object originalObj, Object changedObj, String keyName, String objName, boolean newNullAble) {
        return getUpdateContent(originalObj, changedObj, keyName, objName, false, newNullAble, null);
    }

    public static String getFiledValue(Object target, String filedKey){
        if(target==null||StringUtils.isBlank(filedKey)){
            return null;
        }
        Field[] fields = target.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if(field.getName().equals(filedKey)){
                try {
                    return castToString(field.get(target));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 对比两个实体类，返回更新信息
     *
     * @param originalObj
     * @param changedObj
     * @param keyName
     * @return
     */
    public static String getUpdateContent(Object originalObj, Object changedObj, String keyName, String objName, boolean orgNullAble,
                                          boolean newNullAble, List<String> filterKeys) {
        String returnValue = "";
        String keyValue = "";
        try {
            String[] keyNames = keyName.split(",");
            if (objName != null && !objName.equals(""))
                returnValue = objName + "-";
            returnValue = returnValue + "[{UNIQUEKEY}]信息变更-";
            Field[] fields = originalObj.getClass().getDeclaredFields();
                for (Field field : fields) {
                field.setAccessible(true);
                if (existValue(keyNames, field.getName()))
                    keyValue += field.getName() + ":" + castToString(field.get(originalObj)) + ";";
                if(filterKeys!=null && filterKeys.contains(field.getName()))continue;
                if (newNullAble && field.get(changedObj) == null) continue;//判断新数据是否允许为空时不匹配
                if (orgNullAble && field.get(originalObj) == null) continue;//判断原始数据是否允许为空时不匹配
                if (field.getType().equals(JGeometry.class)) {
                    LOGGER.warn("更新日志不记录空间信息：" + JSONObject.toJSONString(
                            field.get(originalObj) + "|" + JSONObject.toJSONString(field.get(changedObj))));
                }
                if (field.get(originalObj) == null) { //先判断是否 为null，以防止null.equals报空指针异常
                    if (field.get(changedObj) != null && !field.get(changedObj).equals("")) {
                        returnValue += field.getName() + "由[" + castToString(field.get(originalObj)) + "]变更为["
                                + castToString(field.get(changedObj)) + "],";
                    }
                } else if (!field.get(originalObj).equals(field.get(changedObj))) {
                    returnValue += field.getName() + "由[" + castToString(field.get(originalObj)) + "]变更为["
                            + castToString(field.get(changedObj)) + "],";
                }
            }
            returnValue = returnValue.replace("{UNIQUEKEY}", keyValue);
        } catch (Exception e) {
            LOGGER.error("getChanges 错误", e);
        }
        return returnValue;
    }

    public static boolean existValue(String[] strs, String val) {
        if (val == null || val.equals("")) return false;
        for (String str : strs) {
            if (str.equals(val)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将不同类型转换为字符串
     *
     * @param val
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String castToString(Object val) {
        String result = "";
        try {
            if (val != null && !"".equals(val)) {
                Class clz = val.getClass();
                if (val.getClass().equals(String.class)) {
                    return (String) val;
                } else if (val instanceof Number || clz.equals(int.class) || clz.equals(long.class)
                        || clz.equals(short.class) || clz.equals(double.class) || clz.equals(Boolean.class)
                        || clz.equals(boolean.class) || clz.equals(byte.class)) {
                    return String.valueOf(val);
                } else if (clz.equals(Date.class)) {
                    return TimeHelper.dateToLongString((Date) val);
                } else if (clz.equals(java.sql.Date.class)) {
                    return TimeHelper.sqlDateToString((java.sql.Date) val, "yyyy-MM-dd HH:mm:ss");
                } else if (clz.equals(JGeometry.class)) {
                    return GeomtryHelper.getGeom2JsonString((JGeometry) val);
                } else if (val instanceof Collection || val instanceof Map || clz.isArray()) {
                    // 列表、数组、map
                    return JSONObject.toJSONString(val);
                } else {
                    return JSONObject.toJSONString(val);
                }
            }
        } catch (Throwable ex) {
            LOGGER.error(JSONObject.toJSONString(val) + "由\"" + val.getClass() + "\"格式转字符串错误！", ex);
        }
        return result;
    }

    @SuppressWarnings("all")
    public static void main(String[] args) {
        castToString(false);
        Integer integer = new Integer(1);
        castToString(integer);
        castToString(new java.sql.Date(123));
        castToString(EnumEjcdsCommon.HANDLE_TYPE_MAIN);
        String[] strs = "123321342341231234235345623143453".split("1");
        System.out.println(strs.getClass().getName());
        strs.getClass().isArray();
        List<Integer> list = new ArrayList();
        Set ss = new HashSet();
        if (list instanceof Collection)
            list.getClass().getSuperclass().isArray();
        byte[] bs1 = {97, 98, 100};
        System.out.println(bs1.getClass().getName());
    }

}
